package com.qf.rbac.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.rbac.sys.entity.SysRole;
import com.qf.rbac.sys.entity.SysRoleDept;
import com.qf.rbac.sys.mapper.SysRoleDeptMapper;
import com.qf.rbac.sys.service.ISysRoleDeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色与部门对应关系 服务实现类
 * </p>
 *
 * @author dongjl
 * @since 2022-04-16
 */
@Service
public class SysRoleDeptServiceImpl extends ServiceImpl<SysRoleDeptMapper, SysRoleDept> implements ISysRoleDeptService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(Long roleId, List<Long> deptIdList) {
        //先删除角色与部门关系
        deleteBatch(new Long[]{roleId});

        if(deptIdList.size() == 0){
            return ;
        }

        //保存角色与菜单关系
        for(Long deptId : deptIdList){
            SysRoleDept sysRoleDeptEntity = new SysRoleDept();
            sysRoleDeptEntity.setDeptId(deptId);
            sysRoleDeptEntity.setRoleId(roleId);

            this.save(sysRoleDeptEntity);
        }
    }

    @Override
    public boolean deleteBatch(Long[] roleIds) {
        return this.removeBatchByIds(Arrays.asList(roleIds));
    }

    @Override
    public List<Long> queryDeptIdList(Long roleId) {
        List<SysRoleDept> list = this.list(new LambdaQueryWrapper<SysRoleDept>().eq(SysRoleDept::getRoleId,roleId));
        List<Long> collect = list.stream().map((Function<SysRoleDept, Long>) sysRoleDept -> sysRoleDept.getDeptId()).collect(Collectors.toList());
        return collect;
    }
}
